Readonly.php

<?php

namespace Fresh;

/**
 * A cute little trait to allow for public-read-only properties on a class
 * 
 * Declare:
 * ```php
 * use Fresh\Readonly;
 * 
 * protected $property; // Publicly, do `$theClass->property` to retrieve... though the public cannot set it.
 * private $r_property; // This instructs the trait.
 * ```
 * 
 * @export(Contribute.readonly)
 */
trait Readonly {

    public function readonly_getProperty($prop){
        if (!property_exists($this,$prop)){
            //pretty close to the standard error if a protected property is accessed from a public scope
            throw new \Error("Undefined property: ".get_class($this)."'::$prop");
            // trigger_error('Undefined property: '.get_class($this).'::\$'.$prop,E_USER_NOTICE);
        }
        
        $allow_read = property_exists($this, 'r_'.$prop );

        if ($allow_read){
            $actual = $this->$prop;
            return $actual;
        }
        
        throw new \Error("Cannot access non-public property '{$prop}' of class '".get_class($this)."'");
    }

    public function __get($prop){
        return $this->readonly_getProperty($prop);
    }
    
}